//index.js
//获取应用实例
const app = getApp();
var common=require("../../common.js");
var timer= null;
Page({
  onShow: function () {
    this.pause=false;
    this.setData({      
      point:app.globalData.point,
    });

    if (parseInt(app.globalData.point) < app.globalData.onePlayNeedPoint){
      this.setData({ 
        tipImg:'../../image/face_fail.jpg',
        tip1:'积分不足',
        tip2: '一局游戏需要' + app.globalData.onePlayNeedPoint+'积分',
        showTip: true, 
        show: true
        });
    }else{
      this.initscene();
    }    
  },
  animation:null,
  next:null,
  data: {    
    titleAnimat: false,
    album: [
      { 'uid': 0, 'album': '/image/2.jpg' }, { 'uid': 0, 'album': '/image/2.jpg' }, { 'uid': 0, 'album': '/image/2.jpg' },
      { 'uid': 0, 'album': '/image/2.jpg' }, { 'uid': 0, 'album': '/image/2.jpg' }, { 'uid': 0, 'album': '/image/2.jpg' }
      ],
    albumShow: ['none', 'none', 'none', 'none', 'none', 'none'],
    selectedIndex:-1,
    selectedUid:0,
    targetUid:0,
    bigImg:'/image/2.jpg',
    showModalStatus:false,
    avatarUrl:'',
    userInfo: {},
    hasUserInfo: false,
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    nowScore:0,
    historyScore:0,
    show:1,
    showTip: false,
    qa: [
      { q: '积分有什么用', a: '消耗积分才可以玩星探游戏' }, 
      { q: '怎样获取积分', a: '分享小程序给您的朋友即可获得积分' }]
  },

  hideTitle:function(){
    clearInterval(this.interval)
    // 执行第二组动画
    this.animation.opacity(0).scale(0).step({ duration: 500 });
    this.setData({
      lightAnimationData2: this.animation.export()
    })
    setTimeout(function () {
      this.setData({ titleAnimat: false })
      this.processTeam(this.next);   
    }.bind(this), 500)   
    //nextStep
  },
  
  /**
   * 弹出层函数
   */
  //出现
  showTip: function () {
    this.setData({ showTip: true })
  },
  //消失
  hideTip: function (e) {
    this.setData({ showTip: false })
  },


  /**
    * 用户点击右上角分享
    */
  onShareAppMessage: function () {
    var that = this;
    return {
      title: '有人@我,听说你对明星很了解，你能找到ta们小时候的样子吗？？？',
	  imageUrl:'../../image/s.jpg',
      path: 'pages/index/index',
      success: function (res) {
        console.log('shareReturn', res);
        var shareTicket = (res.shareTickets && res.shareTickets[0]) || ''
        /* 官网的Tip: 由于策略变动，小程序群相关能力进行调整，
         * 开发者可先使用wx.getShareInfo接口中的群ID进行功能开发。
         */
        wx.getShareInfo({
          // 把票据带上
          shareTicket: shareTicket,
          success: function (res) {
            wx.showLoading({title:'正在分享'})
            common.request({
              url: 'c=Game&a=descriptShare', data: { data: res.encryptedData, iv: res.iv },
              success: function (e) {
                if (e.status == 0 && e.point > 0) {
                  wx.showToast({
                    title: '获得积分' + e.point,
                    icon: 'success'
                  })
                  app.globalData.point = parseInt(e.point) + parseInt(app.globalData.point);

                  if (parseInt(app.globalData.point) >= app.globalData.onePlayNeedPoint) {
                    that.setData({
                      tipImg: '../../image/face_suc.jpg',
                      tip1: '积分足够,再玩一次吧',
                      tip2: '一局游戏需要500积分',                                          
                    });
                  }
                }
              },complete:function(){
				  wx.hideLoading();
			  }, method: "post"
            });
          }
        })
      },
      fail: function (ret) {
        console.log('cancelShare', ret);
      }
    }
  },
  onLoad: function () {    
    this.setData({
      shareGot: app.globalData.oneShareGotPoint
    })
    wx.showShareMenu({
      withShareTicket: true,
      success: function (res) {
      },
      fail: function (res) {
      }
    })

    

    if (app.globalData.userInfo) {
      this.setData({
        avatarUrl: app.globalData.userInfo.avatarUrl,
        userInfo: app.globalData.userInfo,
        hasUserInfo: true,
        historyScore: app.globalData.historyScore
      })
    } else if (this.data.canIUse) {
      // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
      // 所以此处加入 callback 以防止这种情况
      app.userInfoReadyCallback = res => {
        this.setData({
          userInfo: res.userInfo,
          hasUserInfo: true
        })
      }
    } else {
      // 在没有 open-type=getUserInfo 版本的兼容处理
      wx.getUserInfo({
        success: res => {
          app.globalData.userInfo = res.userInfo
          this.setData({
            userInfo: res.userInfo,
            hasUserInfo: true
          })
        }
      })
    }
  },
  startCountDown:function(){
    this.setData({
      num: app.globalData.timeLimit
    })
    this.pause=false;
    this.countdown(this);
  },
  pause:false,
  countdown:function(that){
    if(this.pause)return false;    
    timer=setTimeout(function () {
      if(that.data.num<=0){        
        that.submitResult(1);
        return;
      }
      that.setData({num:that.data.num-1})
      that.countdown(that);
    }, 1000);
  },
  selectPhoto:function(e){//选中图片
    var index=parseInt(e.currentTarget.dataset.id);
    var reset=false
    if (this.data.albumShow[index] == "none") {
      reset=true      
    }else{
      this.data.selectedIndex = -1;
      this.data.selectedUid=0;
    }

    this.data.albumShow = ['none', 'none', 'none', 'none', 'none', 'none'];
    if(reset){
      this.data.albumShow[index] = "block";
      this.data.selectedIndex = index;
      this.data.selectedUid = e.currentTarget.dataset.uid;
    }
    this.setData({
      albumShow: this.data.albumShow
    })
  },
  //显示大图
  showBigImg: function (e) {
    var currentStatu = e.currentTarget.dataset.statu;
    if (typeof currentStatu =='undefined'){
      
      if(e.currentTarget.id=='avatar'){
        this.setData({
          bigImg: e.currentTarget.dataset.src
        })
      }else{
        var index = parseInt(e.currentTarget.dataset.id);
        this.setData({
          bigImg: this.data.album[index].album
        })
      } 
      this.util('open')
    }else{
      this.util(currentStatu)
    }
  },
  interval:null,
  titleMovie:function(title){//获得称号背景光芒动画
    this.setData({
      titleAnimat: true,
      title: title,
    })

    this.animation = wx.createAnimation({
        duration: 4000, //动画时长
        timingFunction: "linear", //线性
        delay: 0 //0则不延迟
    });
    
    var time=4000
    var count=0;

//光晃动
    this.animation.scale(1.1).rotate(-3).step({ duration: time });
    this.setData({
      lightAnimationData: this.animation.export()
    })

//ICON隐藏
    this.animation.scale(0).opacity(0).rotate(0).step({ duration: 1 });
    this.setData({
      lightAnimationData2: this.animation.export()
    })

//ICON出现
    setTimeout(function () {
      // 执行第二组动画
      this.animation.opacity(1).scale(1).step({ duration: 500 });
      this.setData({
        lightAnimationData2: this.animation.export()
      })
    }.bind(this), 300)   


    this.interval=setInterval(
      function(){
        if(count==0){
          this.animation.scale(1.2).rotate(3).step({ duration: time });
        }else{
          this.animation.scale(1.1).rotate(-3).step({ duration: time });
        }
        this.setData({
          lightAnimationData: this.animation.export()
        })
        count = 1-count;

      }.bind(this), time
    )


  },
  //显示大图的动画效果
  util: function (currentStatu) {
    /* 动画部分 */
    // 第1步：创建动画实例
    var animation = wx.createAnimation({
      duration: 200, //动画时长
      timingFunction: "linear", //线性
      delay: 0 //0则不延迟
    });

    // 第2步：这个动画实例赋给当前的动画实例
    this.animation = animation;

    // 第3步：执行第一组动画
    this.animation.opacity(1).rotateX(-90).step();
    
    // 第4步：导出动画对象赋给数据对象储存
    this.setData({
      animationData: this.animation.export()
    })

    //第5步：设置定时器到指定时候后，执行第二组动画
    setTimeout(function () {
      // 执行第二组动画
      this.animation.opacity(1).rotateX(0).step();
      //animation.opacity(1).rotateX(360).scale(2, 2).step()
      // 给数据对象储存的第一组动画，更替为执行完第二组动画的动画对象
      this.setData({
        animationData: this.animation.export()
      })

      //关闭
      if (currentStatu == "close") {
        this.setData(
          {
            showModalStatus: false
          }
        );
      }
    }.bind(this), 200)

    // 显示
    if (currentStatu == "open") {
      this.setData(
        {
          showModalStatus: true
        }
      );
    }
  },
  getRand:function(){
    return Math.ceil(Math.random()*10000);
  },
  processTeam:function(re){
    if (typeof re=='string') return false;
    var that=this;
    var data=re.list;
    for (var j = 0, len = data.length; j < len; j++) {
      if (typeof data[j].headPic !== "undefined") {
        that.data.targetUid = data[j].uid;
        that.setData({
          avatarUrl: data[j].headPic
        });
        break;
      }
    }
    that.data.album = data;
    that.data.albumShow = ['none', 'none', 'none', 'none', 'none', 'none'];
    that.setData({
      album: that.data.album,
      albumShow: that.data.albumShow,
      target:re.starName
    });
    that.startCountDown();
  },

  startStarGame:function(){
    var that=this;
	wx.showLoading({title:'加载中...'})
    common.request({
      url: 'c=Game&a=startStarGame',
      success: function (e) {    
        app.globalData.point=e.point; 
        that.setData({ point: app.globalData.point});
        that.processTeam(e.next);        
      },complete:function(){
				  wx.hideLoading();
			  },
      method: "POST"
    });
  },
  submitResult: function (isAuto) {
    if (isAuto !=1 && this.data.selectedUid==0){
		  wx.showToast({
			image:'../../image/warn.png',
            title: '请选择目标',
          })
		  return;
	}
    wx.showLoading({
      title: '正在提交',
	  mask:true,
    });
    this.pauseTimer();
    var that = this;
    common.request({
      url: 'c=Game&a=submitStarResult',
      data: {
        gid: this.getRand(),
        oid: this.data.targetUid,
        uid: this.getRand(),
        sid: this.data.selectedUid
      },
      success: function (e) {
        if(e.result!=1){
          that.setData({
            showTip:true,
            tipImg:'../../image/face_fail.jpg',
            tip1:'选择错误！！',
            tip2:'长按图片，可看大图唷'           
            })          
        }else{
          app.globalData.historyScore = e.historyScore;
          app.globalData.point = e.point
          that.setData({
            historyScore: app.globalData.historyScore,
            nowScore: e.nowScore,
            point: app.globalData.point
          })


          if(typeof e.title!='undefined'){
            that.titleMovie(e.title);
            that.next = e.next;
          }else{
            wx.showToast({
              title: '正确',
            })
            that.processTeam(e.next);      
          }    
        }       
      },
      complete: function (ret){ 
        that.data.selectedUid=0;
        wx.hideLoading();
      },
      method: "POST"
    });
  },
  /**
 * 生命周期函数--监听页面隐藏
 */
  onHide: function () {
      this.pauseTimer();
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    this.pauseTimer();
  },
  pauseTimer:function(){
	clearTimeout(timer);
    this.pause=true;
  },
  initscene: function () {
    var smallWait=300;
    var beginScale=0.01;
    var beginPos=150;
    var endPos=250;
    var disPos=300;
    var start=500;
    const appearTime=300;
    const disappearTime=500;
    const stayTime=700;

    //第1步：创建动画实例
    var animation = wx.createAnimation({
      duration: 10, //动画时长
      timingFunction: "linear", //线性
      delay: 0 
    });
    this.animation=animation;

    this.animation.opacity(0).top(beginPos).scale(beginScale).step();

    var a = this.animation.export();
    console.log(a)
    this.setData({
      beginAnimationData3: a
    })
    start += smallWait   

    setTimeout(function () {
      this.animation.opacity(1).top(endPos).scale(1).step({ timingFunction: "linear", duration: appearTime });//
      this.setData({
        beginAnimationData3: this.animation.export()
      })
    }.bind(this), start)
    start += appearTime + stayTime
    //return false;
    
    setTimeout(function () {
      this.animation.opacity(0).top(disPos).scale(13.5).step({ timingFunction: "linear", duration: disappearTime });//
      this.setData({
        beginAnimationData3: this.animation.export()
      })
    }.bind(this), start)
    start += disappearTime+100

/////////////////////////2222222222///////////////////////////////////////////////////////////////////////////
    

    setTimeout(function () {
      this.animation.opacity(0).top(beginPos).scale(beginScale).step();
      this.setData({
        beginAnimationData2: this.animation.export()
      })
    }.bind(this), start)
    start += smallWait
   
    
    setTimeout(function () {
      this.animation.opacity(1).top(endPos).scale(1).step({ timingFunction: "linear", duration: appearTime });//
      this.setData({
        beginAnimationData2: this.animation.export()
      })
    }.bind(this), start)
    start += appearTime + stayTime
    //return false;


    setTimeout(function () {
      this.animation.opacity(0).top(disPos).scale(13.5).step({ timingFunction: "linear", duration: disappearTime });//
      this.setData({
        beginAnimationData2: this.animation.export()
      })
    }.bind(this), start)
    start += disappearTime
    /////////////////////////////11111111///////////////////////////////////////////////

    setTimeout(function () {
      this.animation.opacity(0).top(beginPos).scale(beginScale).step({ duration: 10 });
      this.setData({
        beginAnimationData1: this.animation.export()
      })
    }.bind(this), start)
    start += smallWait


    setTimeout(function () {
      this.animation.opacity(1).top(endPos).scale(1).step({ timingFunction: "linear", duration: appearTime });
      this.setData({
        beginAnimationData1: this.animation.export()
      })
    }.bind(this), start)
    start += appearTime + stayTime

    //放大并消失
    setTimeout(function () {
      this.animation.opacity(0).top(disPos).scale(13.5).step({ timingFunction: "linear", duration: disappearTime });
      this.setData({
        beginAnimationData1: this.animation.export()
      })
    }.bind(this), start)

    start += disappearTime
    ////////////////////////////////////////////////////
    start += 500
    setTimeout(function () {
      this.animation.opacity(0).step({ duration: 1500 });
      this.setData({
        animationModal: this.animation.export()
      })
      this.startStarGame()
    }.bind(this), start)
    start += 500
    /////////////////////////////////////
    
    setTimeout(function () {
      this.setData({
        show: 0
      });
      
    }.bind(this), start)

  },
  tryTap:function(){
    if (parseInt(app.globalData.point) < app.globalData.onePlayNeedPoint){
      wx.showToast({
        title: '积分不足',
        image:'../../image/warn.png'
      })
      return false;
    }
    wx.navigateTo({
      url: '../star/play',
    })
  },
  homeTap:function(){
    //this.titleMovie("测试称号"); return;    
    wx.navigateTo({
      url: '../index/index',
    })
  },
  rankTap: function () {
    wx.navigateTo({
      url: '../star/rank',
    })
  },

});

